//
//  WBComposeVC.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/5/15.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeVC: UIViewController {

    @IBOutlet weak var textView: UITextView!
    
    @IBOutlet weak var toolBar: UIToolbar!
    
    @IBOutlet var sendBtn: UIButton!
    
    @IBOutlet var titleLabel: UILabel!
    
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    // MARK: -- 发布按钮的点击事件
    @IBAction func sendBtnClick(_ sender: UIButton) {
        
        guard let text = textView.text else{
            
            return
        }
        
        WBNetworkManager.shared.postStatus(text: text) { (result, isSuccess) in
            
            let tips = isSuccess ? "发布成功" : "网络不给力"
            
            SVProgressHUD.setDefaultStyle(.dark)
            
            SVProgressHUD.showInfo(withStatus: tips)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: { 
                
                self.close()
                
                SVProgressHUD.setDefaultStyle(.light)
            })
        }
    }
    
    
//    lazy var sendBtn: UIButton = {
       
//        let btn = UIButton()
//        
//        btn.setTitle("发布", for: [])
//        
//        //设置字体颜色
//        btn.setTitleColor(UIColor.white, for: [])
//        btn.setTitleColor(UIColor.darkGray, for: .highlighted)
//        btn.setTitleColor(UIColor.darkGray, for: .disabled)
//        
//        //设置背景图片
//        btn.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), for: .disabled)
//        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
//        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
//        
//        return btn
//    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //发送通知,改变加盘的frame
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    // MARK: -- 视图将要出现的方法
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //成为第一响应
        textView.becomeFirstResponder()
    }

    //为了体验delegate一对一的关系
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//        
//        textView.delegate = self
//    }
    
    // MARK: -- 视图将要消失的方法
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //辞去第一响应
        textView.resignFirstResponder()
    }
    
   
    
    // MARK: -- 关闭当前控制器
    @objc private func close(){
        
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: -- 控制器销毁的时候调用的方法
    deinit {
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
}

fileprivate extension WBComposeVC{
    
    func setupUI() {
        
        //添加左item
        let close = "close"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: Selector(close))
        
        //添加titleView
        navigationItem.titleView = titleLabel
        
        //添加右item
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        sendBtn.isEnabled = false
        
        setupToolBar()
    }
    
    
    func setupToolBar() {
        
        //图片数组
        let images = [["imageName": "compose_add_background"],
                      ["imageName": "compose_camerabutton_background"],
                      ["imageName": "compose_emoticonbutton_background"],
                      ["imageName": "compose_keyboardbutton_background"],
                      ["imageName": "compose_mentionbutton_background"],
                      ]
        
        /// 用来存放item的数组
        var items = [UIBarButtonItem]()
        
        for dict in images {
            
            let btn = UIButton()
            
            guard let imageName = dict["imageName"] else {
                
                continue
            }
            
            let imageHL = imageName + "_highlighted"
            
            btn.setImage(UIImage(named: imageName), for: [])
            btn.setImage(UIImage(named: imageHL), for: .highlighted)
            
            btn.sizeToFit()
            
            items.append(UIBarButtonItem(customView: btn))
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
}

// MARK: - UITextViewDelegate
extension WBComposeVC: UITextViewDelegate{
    
    //当textView的内容发生变化时,调用的方法
    func textViewDidChange(_ textView: UITextView) {
        
        sendBtn.isEnabled = textView.hasText
    }
}

// MARK: - 利用通知,去改变键盘的高度
fileprivate extension WBComposeVC{
    
    @objc func keyBoardChangeFrame(n: Notification){
        
        /// 获取键盘的高度
        guard let rect = (n.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue)?.cgRectValue,
              let duration = (n.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? NSNumber)?.doubleValue
            else{
            
            return
        }
  
        let keyBoardHeight = rect.origin.y
        
        toolBarBottomCons.constant = view.bounds.height - keyBoardHeight
        
        UIView.animate(withDuration: duration) { 
            
            self.view.layoutIfNeeded()
        }
    }
}
